package com.tarry.shop.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarry.shop.exception.BusinessException;
import com.tarry.shop.goods.entity.Goods;
import com.tarry.shop.goods.entity.GoodsImage;
import com.tarry.shop.goods.mapper.IGoodsImageMapper;
import com.tarry.shop.goods.mapper.IGoodsMapper;
import com.tarry.shop.goods.mq.sender.GoodsSender;
import com.tarry.shop.goods.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author TARRY
 * @since 2021-11-27
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<IGoodsMapper, Goods> implements IGoodsService {

    @Resource
    private IGoodsMapper goodsMapper;

    @Resource
    private IGoodsImageMapper goodsImageMapper;

    @Autowired
    private GoodsSender goodsSender;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(Goods goods){
        int insert = goodsMapper.insert(goods);
        List<GoodsImage> images = goods.getImages();
        int imageResult = 0;
        for (int i = 0; i < images.size(); i++) {
            GoodsImage goodsImage = images.get(i);
            goodsImage.setGoodsId(goods.getId());
            imageResult += goodsImageMapper.insert(goodsImage);
        }
        if( imageResult != images.size() || insert == 0){
            throw new BusinessException("保存商品信息异常异常");
        }
        goodsSender.sendGoodsInfo(goods);
        return true;
    }

    @Override
    public IPage<Goods> page(IPage<Goods> page,Goods param){
        return this.goodsMapper.queryList(page, param);
    }


}
